import fs from 'fs'
import request from 'request';
import path from 'path'
import Bagpipe from 'bagpipe'

/**
 * 实现下载
 *
 * @param taskDesc 任务详细
 * @param task 任务
 * @param downloadDir 下载目录
 * @param event
 */
export function doDownload(taskDesc, task, event) {
    const downloadDir = task.downloadDir;
    const bagpipe = new Bagpipe(40);

    let zoomdatadesc = taskDesc.zoomdatadesc;
    let hearder = taskDesc.hearder;
    let urlMiddel = taskDesc.urlMiddel;
    let styleStr = taskDesc.styleJson;
    let urlEnd = styleStr.length == 0 ? '&customid=undefined' : '&styles=' + encodeURIComponent(styleStr);

    const currentDownload = taskDesc.currentDownload;
    let totalCount = taskDesc.totalCount;

    var currCount = 0
    for (let index = 0; index < zoomdatadesc.length; index++) {
        let temp = zoomdatadesc[index];
        let zoomLevel = temp.zoomLevel;

        if (typeof currentDownload.zoomLevel != 'undefined') {
            // 不是undefined的时候，说明已经下载过一部分，现在继续下载

            if (currentDownload.zoomLevel > zoomLevel) {
                currCount = currCount + temp.totalCount;
                continue;
            }
        } else {
            currentDownload.zoomLevel = zoomLevel;
            currentDownload.left = -10000;
            currentDownload.top = -10000;
        }

        let left = temp.left < currentDownload.left ? currentDownload.left : temp.left;
        let right = temp.right;
        let top = temp.top < currentDownload.top ? currentDownload.top : temp.top;
        let bottom = temp.bottom;
        currCount = currCount < currentDownload.totalCountCurr ? currentDownload.totalCountCurr:currCount;
        for (let x = left; x <= right; x++) {
            for (let y = top; y <= bottom; y++) {

                let url = hearder + '&x=' + x + '&y=' + y + '&z=' + zoomLevel + urlMiddel + urlEnd;

                let name = y + '.jpg';
                let dir = zoomLevel + '/' + x;
                let dirname = downloadDir+ '/' + task.taskName + '/' + dir;
                let downloadFullPath = downloadDir + '/' + task.taskName + '/' + dir + '/' + name;


                // try{
                //     console.log(global.tasksMap[''+task.taskId].status);
                //     console.log(global.tasksMap[''+task.taskId].status === 'stop');
                //     console.log(currCount);
                //     console.log(totalCount);
                //     if(global.tasksMap[''+task.taskId] &&
                //         global.tasksMap[''+task.taskId].status === 'stop') {
                //
                //     } else {
                //
                //     }
                // } catch (e) {
                //     console.log(e);
                // }

                bagpipe.push(
                    downloadImage, url, dirname, downloadFullPath, function (err, downloadFullPath) {
                        currentDownload.left = x;
                        currentDownload.top = y;
                        currentDownload.totalCountCurr++;
                        currCount++;

                        let mod = 10;
                        if(task.dataTotalCount < 2000){
                            mod = 10;
                        } else if(task.dataTotalCount < 10000){
                            mod = 50;
                        } else if(task.dataTotalCount < 100000){
                            mod = 100;
                        }

                        if(currCount%mod==0 || currCount >= task.dataTotalCount){
                            // 界面进度条修改，这里还没有处理好
                            task.progress = (currCount / totalCount * 100).toFixed(2);
                            event.sender.send('taskProgressChange', task);
                        }
                    }
                );
            }
        }

        //循环结束后，上左的坐标重置为-1
        currentDownload.left = -10000;
        currentDownload.top = -10000;
        //级别加1
        currentDownload.zoomLevel++;
    }
}

function downloadImage(url, dirname, downloadFullPath, callback) {
    // 文件不存在，就下载
    if (!fs.existsSync(downloadFullPath)) {
        if (mkdirSync(dirname)) {
            request.head(url, function (err, res, body) {
                if (url) {
                    request(url).pipe(fs.createWriteStream(downloadFullPath)).on('close', function () {
                        callback(null, downloadFullPath);
                    });
                }
            });
        }
    }else{
        callback(null, downloadFullPath);
    }
};

function mkdirSync(dirname) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
    return false
}